package cn.cuiliangpeng.basic.exception;

import cn.cuiliangpeng.basic.utils.AjaxResult;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;
/**
 * 全局异常处理
 */
@RestControllerAdvice//对所有加了RequestMapping的类进行增强
public class GlobalExceptionHandler {
    @ExceptionHandler(BusinessException.class)//捕获指定的异常
    public AjaxResult BusinessExceptionHandler(BusinessException e){
        e.printStackTrace();
        //通过code获取枚举对象
        ErrorCode error = ErrorCode.getByCode(e.getMessage());
        return AjaxResult
                .me()
                .setCode(error.getCode())
                .setSuccess(false)
                .setMessage(error.getMessage());
    }
    /**
     * 捕获非业务异常
     * @param e
     * @return
     */
    @ExceptionHandler(Exception.class)//使用异常类的祖先类可以捕获其子类的异常
    public AjaxResult exceptionHandler(Exception e){
        e.printStackTrace();
        return AjaxResult
                .me()
                .setCode(ErrorCode.SYSTEM_ERROR.getCode())
                .setSuccess(false)
                .setMessage(ErrorCode.SYSTEM_ERROR.getMessage());
    }
}
